package cn.e3mall.cart.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.e3mall.common.util.CookieUtils;
import cn.e3mall.common.util.E3Result;
import cn.e3mall.pojo.TbUser;
import cn.e3mall.sso.service.TokenService;

public class LoginInterceptor implements HandlerInterceptor {
	@Autowired
	private TokenService tokenService;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		// 前处理,执行handler之前执行
		//返回true,放行,返回false拦截
		//从cookie中取token
		String token = CookieUtils.getCookieValue(request, "token");
		//没有token未登录状态,直接方向
		if(StringUtils.isBlank(token)){
			return true;
		}
		//驱动token,条用sso系统取用户的信息,根据token取用户信息
		E3Result result = tokenService.getUserByToken(token);
		//没有取到用户信息,登录过期,直接放行
		if(result.getStatus()!=200){
			return true;
		}
		//取到用户信息.登录状态
		TbUser user = (TbUser) result.getData();
		//把用户信息放到request中,只需要在controller中判断request中是否包含用户信息,放行
		request.setAttribute("user",user);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView modelAndView) throws Exception {
		// handler之后返回modelandview之前

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception exception)
					throws Exception {
		// 返回modelandview之后可以在此处理异常
		
	}

}
